/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package us.levk.tools.collections;

import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;


/**
 * <p>A List wrapper that does not support destructive operations</p>
 *
 * @author levk
 *
 */
public class NonDestructiveList<E> extends AbstractList<E> {

  private final List<E> wrapped;

  public NonDestructiveList (List<E> wrapped) { this.wrapped = wrapped; }

  /* (non-Javadoc)
   * @see java.util.AbstractList#get(int)
   */
  @Override public E get (int index) { return wrapped.get (index); }

  /* (non-Javadoc)
   * @see java.util.AbstractCollection#size()
   */
  @Override public int size () { return wrapped.size (); }

  /* (non-Javadoc)
   * @see java.util.AbstractList#add(int, java.lang.Object)
   */
  @Override public void add (int index, E element) { wrapped.add (index, element); }

  /* (non-Javadoc)
   * @see java.util.AbstractList#iterator()
   */
  @Override public Iterator<E> iterator () { return listIterator (); }

  /* (non-Javadoc)
   * @see java.util.AbstractList#listIterator()
   */
  @Override public ListIterator<E> listIterator (final int index) {
    return new ListIterator<E> () {
      private final ListIterator<E> that = wrapped.listIterator (index);

      @Override public boolean hasNext () { return that.hasNext (); }

      @Override public E next () { return that.next (); }

      @Override public boolean hasPrevious () { return that.hasPrevious (); }

      @Override public E previous () { return that.previous (); }

      @Override public int nextIndex () { return that.nextIndex (); }

      @Override public int previousIndex () { return that.previousIndex (); }

      @Override public void remove () { throw new UnsupportedOperationException (); }

      @Override public void set (E e) { throw new UnsupportedOperationException (); }

      @Override public void add (E e) { that.add (e); }
    };
  }

  /* (non-Javadoc)
   * @see java.util.AbstractList#subList(int, int)
   */
  @Override public List<E> subList (int fromIndex, int toIndex) { return new NonDestructiveList<E> (wrapped.subList (fromIndex, toIndex)); }
}
